var express = require('express');
var router = express.Router();

var fs = require('fs')

var PATH = './public/data/'
/* GET home page. */

// data/read?type=it
// 获取数据接口
router.get('/read', function(req, res, next) {
  var type = req.param('type') || ''
  fs.readFile(PATH + type + '.json', function(err, data) {
    if(err){
      return res.send({
        status: 0,
        info: '读取文件出现异常'
      })
    }
    var COUNT = 50
    var obj = []
    try{
      obj = JSON.parse(data.toString())
    }catch (e) {
      obj =[]
    }
    if(obj.length > COUNT) {
      obj = obj.slice(0, COUNT)
    }
    return res.send({
      status:1,
      data: obj
    })
  })
});

//数据存储模块接口（后台开发使用）
router.post('/write', function(req, res, next) {
  if(!req.session.user) {
    return res.send({
      status: 0,
      info: '未登录'
    })
  }
  //文件名
  var type = req.param('type') || ''
  //关键字段
  var url = req.param('url') || ''
  var title = req.param('title') || ''
  var img = req.param('img') || ''
  if(!type || !url || !title || !img) {
    return res.send({
      status: 0,
      info: '提交的字段不全'
    })
  }
  //读取文件
  fs.readFile(PATH + type + '.json', function(err, data) {
    if(err){
      return res.send({
        status: 0,
        info: '读取数据失败'
      })
    }
    var arr = JSON.parse(data.toString())
    var obj = {
      img: img,
      url: url,
      title: title,
      id: guidGenerate(),
      time: new Date()
    }
    arr.splice(0,0,obj)
      //写入文件
    var newData = JSON.stringify(arr)
    fs.writeFile(PATH + type + '.json', newData, function(err, data) {
      if(err) {
        return res.send({
          status: 0,
          info: '写入失败'
        })
      }
      return res.send({
        status: 1,
        info: obj
      })
    })
  })
})

//阅读模块配置写入接口（后台开发使用）
router.post('/write_config', function(req, res, next) {
  if(!req.session.user) {
    return res.send({
      status: 0,
      info: '未登录'
    })
  }
  //后期进行提交数据的验证
  //防xss攻击
  //npm install xss
  //require('xss)
  // var str = xss(name)
  var data = req.body.data
  var obj = JSON.parse(data)
  var newData = JSON.stringify(obj)
  //写入文件
  fs.writeFile(PATH + 'config.json', newData, function(err, data) {
    if(err) {
      return res.send({
        status: 0,
        info: '写入数据失败'
      })
    }
    return res.send({
      status: 1,
      info: obj
    })
  })
})

//登录接口
router.post('/login', function(req, res, next) {
  var username = req.body.username
  var password = req.body.password
  console.log(req.body)
  //xss处理/判空
  //密码加密  md5(passworld + '随机字符串')
  if(username === 'admin' && password === '123456') {
    req.session.user ={
      username: username
    }
    return res.send({
      status: 1,
      info: '登录成功'
    })
  }
  return res.send({
    status: 0,
    info: '登录失败，请检查用户名或密码是否正确'
  })
})

function guidGenerate() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0,
    v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  }).toUpperCase();
}

module.exports = router;